package org.dyndns.blackpaw.whirlmon;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

@SuppressWarnings("unused")
public class NewsFragment extends ListFragment {

	static final String LOGTAG = "NEWS";

	class WPNewsArrayAdapter extends ArrayAdapter<WPNews> {
		public WPNewsArrayAdapter(Context context, WPNews.List newsItems) {
		    super(context, R.layout.news_row_view, newsItems);
		}

        SimpleDateFormat dateDayFormat = new SimpleDateFormat("EEEE");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd");
		
	    @Override
	    public android.view.View getView(int position, View convertView,
	            ViewGroup parent) {

	        LayoutInflater inflater = (LayoutInflater) getContext()
	                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

	        View listItemView = convertView;
	        if (null == convertView) {
	            listItemView = inflater
	                    .inflate(R.layout.news_row_view, parent, false);
	        }

            WPNews t = (WPNews) getItem(position);
            LinearLayout viewSeperator = (LinearLayout) listItemView
                    .findViewById(R.id.news_separator);
            TextView viewSepDay = (TextView) listItemView
                    .findViewById(R.id.news_separator_day);
            TextView viewSepDate = (TextView) listItemView
                    .findViewById(R.id.news_separator_date);
	        TextView viewTitle = (TextView) listItemView
	                .findViewById(R.id.news_title);
            TextView viewSource = (TextView) listItemView
                    .findViewById(R.id.news_source);
	        TextView viewBlurb = (TextView) listItemView
	                .findViewById(R.id.news_blurb);

	        boolean sectionStart = (position == 0);
	        if (! sectionStart)
	        {
	            // Check previous item
	            WPNews prev = (WPNews) getItem(position - 1);
	            sectionStart = (t.date.getDay() != prev.date.getDay());
	        }
	        if (sectionStart)
	        {
	            viewSeperator.setVisibility(View.VISIBLE);
	            viewSepDay.setText(dateDayFormat.format(t.date));
                viewSepDate.setText(dateFormat.format(t.date));
	        }
	        viewTitle.setText(t.title);
            viewSource.setText(t.source);
	        viewBlurb.setText(t.blurb);

	        return listItemView;
	    }
		
	}

	WPNewsArrayAdapter adaptor;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(LOGTAG, "onCreateView");
		setHasOptionsMenu(true);
		View v = inflater.inflate(R.layout.news, container, false);
		return v;
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		DoOnItemClick(l, v, position, id);
	}

	protected void DoOnItemClick(AdapterView<?> av, View view, int i, long l) {
	    final WPNews news = adaptor.getItem(i);
		// http://whirlpool.net.au/news/go.cfm?article=66794
		Uri uriUrl = Uri.parse("http://whirlpool.net.au/news/go.cfm?article="
				+ news.id);
		Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
		startActivity(launchBrowser);
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		RefreshNews();
	}

	@Override
	public void onStop() {
		if (currentTask != null)
			currentTask.cancel(true);
		super.onStop();
	}

	private class NewsTask extends AsyncTask<String, Void, Void> {

		WPNews.List w = null;

		@Override
		protected void onPreExecute() {
			getActivity().setProgressBarIndeterminateVisibility(true);
		}

		@Override
		protected Void doInBackground(String... params) {
			try {

				String apiKey = params[0];
				w = WPNews.getNews(apiKey);
			} catch (Throwable x) {
				Log.e(LOGTAG, "NewsTask", x);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			currentTask = null;
			if (getActivity() == null) {
				Log.i(LOGTAG, "onPostExecute - Activity stopped");
			} else {
				getActivity().setProgressBarIndeterminateVisibility(false);
				UpdateNewsUI(w);
			}
		}

		@Override
		protected void onCancelled() {
			Log.i(LOGTAG, "Cancelled");
			currentTask = null;
			super.onCancelled();
		}
	}

	NewsTask currentTask = null;

	private void RefreshNews() {
		if (currentTask != null)
			currentTask.cancel(true);
		SharedPreferences sharedPrefs = PreferenceManager
				.getDefaultSharedPreferences(getActivity());
		String apiKey = sharedPrefs.getString("api_key", "");
		currentTask = new NewsTask();
		currentTask.execute(apiKey);
	}

	private void UpdateNewsUI(WPNews.List news) {
		Log.i(LOGTAG, "UpdateNews");
		try {
			if (news == null)
				throw new Exception("No data");

			adaptor = new WPNewsArrayAdapter(getActivity(), news);
			setListAdapter(adaptor);
		} catch (Throwable x) {
			Log.e(LOGTAG, "UpdateNews", x);
		}

	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.recent_menu, menu);
		MenuItemCompat.setShowAsAction(menu.findItem(R.id.refresh),
				MenuItemCompat.SHOW_AS_ACTION_IF_ROOM);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh:
			RefreshNews();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
